package com.seamtop.cuber.web.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seamtop.cuber.common.entriy.CuberContants;
import com.seamtop.cuber.common.entriy.HttpReturn;
import com.seamtop.cuber.common.entriy.ValidateConstants;
import com.seamtop.cuber.common.metadata.Column;
import com.seamtop.cuber.common.metadata.TableMetaData;
import com.seamtop.cuber.common.params.ParamsCalibration;
import com.seamtop.cuber.common.util.*;
import com.seamtop.cuber.common.entriy.User;
import com.seamtop.cuber.web.service.UserManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by feng on 2015/9/9.
 */
@Controller("UserController")
public class UserController {

    @Autowired
    private UserManagerService userManagerService;

    @RequestMapping("/user/addUserIndex.shtml")
    public String addUserIndex(HttpServletRequest request, HttpServletResponse response,
                               ModelMap model) {
        model.addAttribute("enkey","1234567812345678");
        return "/user/user_add_index";
    }


    @RequestMapping("/user/addUser.shtml")
    public @ResponseBody
    HttpReturn addUser(HttpServletRequest request) {
        HashMap<String,String> paramsMap = ParamsUtil.transRequestToMap(request);
        HttpReturn httpReturn = ParamsCalibration.validate(ValidateConstants.VALIDATE_ID_ADD_USER, paramsMap);
        if(CuberUtil.isValidateError(httpReturn)){
            return httpReturn;
        }

        try{
            String userName = paramsMap.get("userName");
            String password = paramsMap.get("password");
            String description = paramsMap.get("description");
            userName = EncryptUtil.desEncrypt(userName, CuberContants.SERVER_ENCRYPT_KEY);
            password = EncryptUtil.desEncrypt(password, CuberContants.SERVER_ENCRYPT_KEY);
            User user = new User();
            user.setUserName(userName);
            int num = userManagerService.isUserExist(user);
            if(num == 0){
                String md5Password = MD5Util.getMD5Code(password);
                user.setPassword(md5Password);
                user.setDescription(description);
                user.setOperatorDate(new Date());
                userManagerService.addUser(user);
                httpReturn.put("result", HttpReturn.RETURN_CODE_SUCCESS);
                httpReturn.put("desc", "add user success");
            }else{
                httpReturn.put("result", HttpReturn.RETURN_CODE_FAILURE);
                httpReturn.put("desc", "user already exists");
            }
        }catch (Exception e){
            e.printStackTrace();
            httpReturn.put("result", HttpReturn.RETURN_CODE_ERROR);
            httpReturn.put("desc", "user add error");
        }
        return httpReturn;
    }

    @RequestMapping("/user/userList.shtml")
    public String findUserList(HttpServletRequest request, HttpServletResponse response,
                               ModelMap model) {
        List<User> userList = userManagerService.findUserList();
        model.addAttribute("userList",userList);
        return "/user/user_list";
    }

    @RequestMapping("/user/getUserInfo.shtml")
    public @ResponseBody
    JSONObject getUserInfo(HttpServletRequest request, HttpServletResponse response,
                              ModelMap model) {
        JSONObject object = new JSONObject();
        String idStr = request.getParameter("id");
        if(!StringUtil.isEmpty(idStr) && StringUtil.isDigital(idStr)){
            User user = userManagerService.getUserInfo(Integer.valueOf(idStr));
            object.put("userName", user.getUserName());
            object.put("password", user.getPassword());
            object.put("description",user.getDescription());
            object.put("id",user.getId());
        }
        return object;
    }

    @RequestMapping("/user/updateUserInfo.shtml")
    public @ResponseBody
    JSONObject updateUserInfo(HttpServletRequest request, HttpServletResponse response,
                              ModelMap model) {
        JSONObject object = new JSONObject();
        String description = request.getParameter("description");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String id = request.getParameter("id");
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setDescription(description);
        user.setUserName(userName);
        user.setPassword(password);
        try{
            userManagerService.updateUserInfo(user);
            object.put("result", "success");
            object.put("desc", "??????????????");
        }catch (Exception e){
            e.printStackTrace();
            object.put("result", "fail");
            object.put("desc", "??????????");
        }
        return object;
    }

    @RequestMapping("/user/resetPassword.shtml")
    public @ResponseBody
    HttpReturn resetPassword(HttpServletRequest request) {
        HashMap<String,String> paramsMap = ParamsUtil.transRequestToMap(request);
        HttpReturn httpReturn = ParamsCalibration.validate(ValidateConstants.VALIDATE_ID_RESET_PASSWORD, paramsMap);
        if(CuberUtil.isValidateError(httpReturn)){
            return httpReturn;
        }
        //is user exists
        User user = new User();
        user.setId(Integer.valueOf(paramsMap.get("userId")));
        user.setUserName(paramsMap.get("userName"));
        int count = userManagerService.isUserExist(user);
        if(count == 0 || count > 1){
            httpReturn.put("result",HttpReturn.RETURN_CODE_FAILURE);
            httpReturn.put("desc","user info error");
            return httpReturn;
        }
        user.setPassword(MD5Util.getMD5Code(CuberContants.USER_RESET_PASSWORD));
        user.setOperatorDate(new Date());
        try{
            userManagerService.updateUserInfo(user);
            httpReturn.put("result", HttpReturn.RETURN_CODE_SUCCESS);
            httpReturn.put("desc", "success");
        }catch (Exception e){
            e.printStackTrace();
            httpReturn.put("result", HttpReturn.RETURN_CODE_ERROR);
            httpReturn.put("desc", "update user password error!");
        }
        return httpReturn;
    }


    @RequestMapping("/user/deleteUserInfo.shtml")
    public @ResponseBody
    HttpReturn deleteUserInfo(HttpServletRequest request) {
        HashMap<String,String> paramsMap = ParamsUtil.transRequestToMap(request);
        HttpReturn httpReturn = ParamsCalibration.validate(ValidateConstants.VALIDATE_ID_DELETE_USER_INFO, paramsMap);
        if(CuberUtil.isValidateError(httpReturn)){
            return httpReturn;
        }
        int id = Integer.valueOf(paramsMap.get("userId"));
        try{
            userManagerService.deleteUserInfo(id);
            httpReturn.put("result", HttpReturn.RETURN_CODE_SUCCESS);
            httpReturn.put("desc", "success");
        }catch (Exception e){
            e.printStackTrace();
            httpReturn.put("result", HttpReturn.RETURN_CODE_ERROR);
            httpReturn.put("desc", "delete user info error!");
        }
        return httpReturn;
    }
}
